<template>
  <el-dialog
    v-model="visible"
    title="操作明细"
    width="80%"
    draggable
    :before-close="closeDialog"
    custom-class="custom-dialog"
  >
    <!-- 日期选择器 -->
    <div class="filter-container">
      <el-form-item label="选择日期范围">
        <el-date-picker
          v-model="startDate"
          type="date"
          placeholder="选择开始日期"
          value-format="YYYY-MM-DD "
          class="date-picker"
          @change="handleDateChange"
        />
        <span class="date-separator">至</span>
        <el-date-picker
          v-model="endDate"
          type="date"
          placeholder="选择结束日期"
          value-format="YYYY-MM-DD "
          class="date-picker"
          @change="handleDateChange"
        />
      </el-form-item>
    </div>
    <div class="flex-container">
      <el-form-item label="物料名称">
        <div class="input-wrapper">
          <el-input
            v-model="materialName"
            placeholder="请输入物料名称"
            clearable
            @input="handleSearch"
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
        </div>
      </el-form-item>

      <el-form-item label="操作员名称">
        <div class="input-wrapper">
          <el-input
            v-model="operatorName"
            placeholder="请输入操作员名称"
            clearable
            @input="handleSearch"
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="操作类型">
        <div class="input-wrapper">
          <el-select
            v-model="selectedOperationType"
            placeholder="请选择操作类型"
            clearable
            @change="handleSearch"
            style="width: 200px"
          >
            <el-option label="入库" value="3" />
            <el-option label="出库" value="2" />
            <el-option label="误差调整" value="4" />
          </el-select>
          <el-button
            type="primary"
            icon="search"
            style="height: 100%"
            @click="handleSearch"
            >查询</el-button
          >
          <el-button icon="refresh" style="width: 80px" @click="resetSearch"
            >重置</el-button
          >
        </div>
      </el-form-item>
    </div>

    <el-table
      :data="filteredData"
      v-loading="loading"
      style="width: 100%; margin-top: 15px"
      class="custom-table"
    >
      <el-table-column
        prop="productName"
        label="产品名称"
        width="120"
        align="center"
        fixed="left"
      />
      <el-table-column
        prop="specification"
        label="产品规格"
        width="150"
        align="center"
        fixed="left"
      />
      <el-table-column label="操作类型" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getTagType(row.operationType)" size="small">
            {{ operationTypeMap[row.operationType] }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="amountBefore"
        label="操作前重量"
        width="120"
        align="center"
      >
        <template #default="{ row }">
          {{ row.amountBefore + "kg" }}
        </template>
      </el-table-column>
      <el-table-column label="重量变动" width="120" align="center">
        <template #default="{ row }">
          <span :style="getAmountStyle(row)">
            {{ formatAmount(row) + "kg" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="amountAfter"
        label="操作后重量"
        width="120"
        align="center"
      >
        <template #default="{ row }">
          {{ row.amountAfter + "kg" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="pieceBefore"
        label="操作前数量"
        width="120"
        align="center"
      >
        <template #default="{ row }">
          {{ row.pieceBefore + "pcs" }}
        </template>
      </el-table-column>
      <el-table-column label="数量变动" width="120" align="center">
        <template #default="{ row }">
          <span :style="getAmountStyle(row)">
            {{ formatPiece(row) + "pcs" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="pieceAfter"
        label="操作后数量"
        width="120"
        align="center"
      >
        <template #default="{ row }">
          {{ row.pieceAfter + "pcs" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="operatorName"
        label="操作员"
        width="80"
        align="center"
        fixed="right"
      />
      <el-table-column
        prop="date"
        label="操作时间"
        width="180"
        align="center"
      />
    </el-table>

    <template #footer>
      <el-button @click="closeDialog">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { computed, defineComponent, ref, watch } from "vue";
import axios from "axios";
import request from "@/utils/request";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";

// 类型定义
interface OperationRecord {
  operationType: number;
  amount: number;
  productName?: string;
  operationDate: string;
  operatorName: string;
  [key: string]: any;
}

export default defineComponent({
  props: {
    dialogVisible: Boolean,
  },
  setup(props, { emit }) {
    const operationTypeMap: Record<number, string> = {
      2: "出库",
      3: "入库",
      4: "调整",
    };

    // 样式处理
    const getTagType = (type: number) => {
      const typeMap: Record<number, "success" | "danger" | "warning"> = {
        3: "success", // 入库
        2: "danger", // 出库
        4: "warning", // 调整
      };
      return typeMap[type] || "info";
    };
    // 过滤有效类型
    const filteredData = computed(() =>
      detailData.value
        .filter((item) => [2, 3, 4].includes(item.operationType))
        .map(formatRecord)
    );

    // 数据格式化
    const formatRecord = (item: OperationRecord) => ({
      ...item,
      date: dayjs(item.operationDate).format("YYYY-MM-DD HH:mm:ss"),
      productName: item.productName || "未命名产品",
    });

    const visible = ref(props.dialogVisible);
    const startDate = ref<string>();
    const endDate = ref<string>();
    const materialName = ref("");
    const operatorName = ref("");
    const selectedOperationType = ref<number | null>(null);

    const detailData = ref<any[]>([]);
    const loading = ref(false);

    // 初始化日期范围
    const initDateRange = () => {
      const now = dayjs();
      startDate.value = now.startOf("month").format("YYYY-MM-DD");
      endDate.value = now.format("YYYY-MM-DD");
    };

    const clearDateFilter = () => {
      initDateRange();
    };

    const fetchData = async () => {
      if (startDate.value && endDate.value && startDate.value > endDate.value) {
        ElMessage.warning("开始日期不能晚于结束日期");
        return;
      } else {
        let data = JSON.stringify({
          startTime: `${startDate.value} 00:00:00`,
          endTime: `${endDate.value} 23:59:59`, // 能获取当天操作
        });
        try {
          const response = await request({
            method: "post",
            url: "inventory/records/getRecordsByRange",
            headers: {
              "Content-Type": "application/json",
            },
            data: data,
          });
          detailData.value = response.data.data;
        } catch (error) {
          console.log(error);
        }
      }
    };

    const handleSearch = async () => {
      if (!startDate.value || !endDate.value) {
        ElMessage.warning("请先选择完整的日期范围");
        return;
      }

      if (startDate.value > endDate.value) {
        ElMessage.warning("开始日期不能晚于结束日期");
        return;
      }

      loading.value = true;
      try {
        const params = {
          startTime: `${startDate.value} 00:00:00`,
          endTime: `${endDate.value} 23:59:59`,
          productName: materialName.value.trim(),
          operatorName: operatorName.value.trim(),
          operationType: selectedOperationType.value,
        };

        const response = await request({
          method: "post",
          url: "inventory/records/getRecordsByPrams",
          headers: {
            "Content-Type": "application/json",
          },
          data: params,
        });
        detailData.value = response.data.data;
      } catch (error) {
        console.log(error);
      }
      loading.value = false;
    };

    const resetSearch = () => {
      materialName.value = "";
      operatorName.value = "";
      selectedOperationType.value = null;
      fetchData();
    };

    const getAmountStyle = (row: OperationRecord) => {
      const colorMap: Record<number, string> = {
        3: "#67C23A", // 入库-绿
        2: "#F56C6C", // 出库-红
        4: "#E6A23C", // 调整-橙
      };
      return { color: colorMap[row.operationType], fontWeight: 500 };
    };

    const formatAmount = (row: OperationRecord) => {
      const prefix = { 2: "-", 3: "+", 4: "±" }[row.operationType];
      return `${prefix}${row.amount}`;
    };
    const formatPiece = (row: OperationRecord) => {
      const prefix = { 2: "-", 3: "+", 4: "±" }[row.operationType];
      return `${prefix}${row.piece}`;
    };

    const handleDateChange = async () => {
      if (startDate.value && endDate.value) {
        await fetchData();
      }
    };

    watch(
      () => props.dialogVisible,
      (newVal) => {
        visible.value = newVal;
        // 打开弹窗时初始化日期范围
        if (newVal) {
          initDateRange();
          fetchData();
        } else {
          clearDateFilter();
        }
      }
    );

    const closeDialog = () => {
      visible.value = false;
      emit("update:dialogVisible", false);
    };

    return {
      visible,
      startDate,
      endDate,
      materialName,
      operatorName,
      selectedOperationType,
      filteredData,
      loading,
      operationTypeMap,
      getTagType,
      getAmountStyle,
      formatAmount,
      formatPiece,
      closeDialog,
      handleDateChange,
      handleSearch,
      resetSearch,
    };
  },
});
</script>

<style scoped>
/* 日期选择器容器 */
.filter-container {
  flex-shrink: 0; /* 防止被压缩 */
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin: 0 auto 15px;
  width: 80%;
  max-width: 800px;
}

.date-picker {
  flex: 1;
  max-width: 300px;
}

.flex-container {
  display: flex;
  flex-flow: row wrap;
  justify-content: center; /* 水平居中 */
  column-gap: 12px;
  align-items: flex-end;
}

.input-wrapper {
  display: flex;
  align-items: center; /* 垂直居中对齐输入框和按钮 */
  gap: 8px; /* 调整输入框与按钮之间的间距 */
}
</style>